package servlets;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.JNDIFactory;

public class ImageController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String errorPicture = "/images/error404.jpg";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		try {

			// TODO: Fehler abfangen
			if (request.getSession().getAttribute("user_id") == null) {
				return;
			}
			if (request.getParameter("image") == null) {
				return;
			}

			String projectPath = JNDIFactory.getInstance()
					.getEnvironmentAsString("projectPath");
			String imagePath = request.getParameter("image");
			String completePath = "";

			if (request.getParameter("thumb") != null)
				if (request.getParameter("thumb").equals("true")) {
					completePath = imagePath.substring(0,
							imagePath.lastIndexOf('/'))
							+ "/thumb"
							+ imagePath.substring(imagePath.lastIndexOf('/'),
									imagePath.length());
				} else {
					completePath = imagePath;
				}
			else {
				completePath = imagePath;
			}

			File file = new File(projectPath + completePath);
			if (!file.isFile()) {
				file = new File(projectPath + errorPicture);
			}
			BufferedImage bi = ImageIO.read(file);
			response.setContentType("image/jpg");

			Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
			ImageWriter writer = (ImageWriter) writers.next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(response
					.getOutputStream());
			writer.setOutput(ios);
			writer.write(bi);
			ios.close();

			return;

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
